# --*--coding=utf-8 --*--
"""
响应模板类
"""
from xml.etree.ElementTree import Element, SubElement, ElementTree
from auto_test.config import CBSConfig
import os


class CbcProxyMsg(object):
    """
    CBC响应报文类
    """

    def __init__(self, msg_id=None, msg_name=None, bank_type=None):
        self.id = msg_id
        self.msg_name = msg_name
        # 默认请求招行的报文
        self.msg_bank_type = bank_type
        self.msg_data = {}
        # 存放代理报文的目录
        self.msg_dir = CBSConfig.TEST_PROXY_MSG_DIR
        self.msg_path = None

    def set_msg_name(self, name):
        """
        CBC的请求报文名
        :param name:
        """
        self.msg_name = name

    def set_msg_data(self, data):
        """
        设置参数变量
        :param data:
        """
        self.msg_data = data

    def set_msg_path(self, child_msg_path):
        """
        :param child_msg_path:
        :return:
        """
        self.msg_path = self.msg_dir + child_msg_path

    def set_msg_bank_type(self, msg_bank_type):
        """
        :param msg_bank_type:
        """
        self.msg_bank_type = msg_bank_type

    def get_msg_xml(self, encoding='GBK'):
        """
        根据报文数据生成CBC的响应报文
        """
        if len(self.msg_data) == 0:
            return
        root_ele = Element("elXmlIniPlus")
        root_ele.text = '\n'
        for section_name, section_list in self.msg_data.items():
            if len(section_list) == 0:
                continue
            if not isinstance(section_list, list):
                return
            section_ele = SubElement(root_ele, "Section")
            section_ele.set("SectionName", section_name)
            section_ele.text = '\n'
            section_ele.tail = '\n'
            for prop_dict in section_list:
                if len(prop_dict) == 0:
                    continue
                if not isinstance(prop_dict, dict):
                    continue
                prop_ele = SubElement(section_ele, "elXmlProperty")
                prop_ele.text = '\n'
                prop_ele.tail = '\n'
                for k, v in prop_dict.items():
                    if v is None:
                        v = ''
                    if not isinstance(v, str):
                        v = str(v)
                    attr_ele = SubElement(prop_ele, "Attribute")
                    attr_ele.set("key", k.strip())
                    attr_ele.set("value", v.strip())
                    attr_ele.tail = '\n'
        tree = ElementTree(root_ele)
        # 删除原有模板报文
        xml_name = self.msg_path + '.xml'
        if os.path.exists(xml_name):
            os.remove(xml_name)
        tree.write(xml_name, encoding=encoding)
        return tree

    def parse_msg_xml(self, xml_parser):
        """
        解析CBC XML报文，生成dict对象
        :param xml_parser:
        """
        self.msg_data = {}
        for sect_ele in xml_parser.getElementsByTagName('Section'):
            prop_list = []
            for prop_ele in sect_ele.getElementsByTagName('elXmlProperty'):
                attr_dict = {}
                for attr_ele in prop_ele.getElementsByTagName('Attribute'):
                    key = attr_ele.getAttribute('key')
                    value = attr_ele.getAttribute('value')
                    attr_dict[key] = value
                prop_list.append(attr_dict)
            self.msg_data.update({sect_ele.getAttribute('SectionName'): prop_list})
        # print(self.msg_data)
        return self.msg_data
